import base64
import datetime
import hashlib
import math
import os
import time
import urllib
import urllib.request
import uuid
from enum import Enum

import pandas as pd
import requests

from server.pao_python.pao.data import dataframe_to_list, date_to_string
from server.pao_python.pao.service.data.mongo_db import (C, F, MongoFilter,
                                                         MongoService, N,
                                                         as_date)

from ...models.financial_manage import FinancialAccount
from ...pao_python.pao.data import get_cur_time, process_db, string_to_date
from ...service.buss_mis.financial_account import FinancialAccountObject
from ...service.buss_pub.bill_manage import (BillManageService, OperationType,
                                             Status, TypeId)
from ...service.buss_pub.import_excel import ImportExcelService
from ...service.buss_pub.personnel_organizational import UserCategory, UserType
from ...service.common import (SecurityConstant, UserType, find_data,
                               get_current_organization_id,
                               get_current_role_id, get_current_user_id,
                               get_info, get_str_to_age, get_string_time,
                               insert_data, update_data, insert_many_data, get_user_id_or_false)
from ...service.constant import (AccountStatus, AccountType, PayStatue,
                                 PayType, plat_id)
from ...service.mongo_bill_service import MongoBillFilter
from ...service.welfare_institution.accommodation_process import CheckInStatus


'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-09-25 09:48:29
@LastEditTime: 2019-10-31 15:50:52
@LastEditors: Please set LastEditors
'''
'''
版权：Copyright (c) 2019 China

创建日期：Tuesday September 17th 2019
创建者：ymq(ymq) - <<email>>

修改日期: Tuesday, 17th September 2019 9:52:29 am
修改者: ymq(ymq) - <<email>>

说明
 1、用户管理服务
'''


class PersonOrgManageService(MongoService):
    '''人员及组织机构管理'''

    user_collection = 'PT_User'
    role_collection = 'PT_Role'
    permission_collection = 'PT_Permission'
    business_collection = 'PT_Business_Area'
    plat_visitor_id = '8ed260f6-e355-11e9-875e-a0a4c57e9ebe'
    project_condition = {
        '_id': 0,
        'name': '$user_info.name',
        'id': '$user_info.id',
        'organization_id': '$user_info.organization_id',
        'id_card': '$user_info.id_card',
        'id_card_type': '$user_info.id_card_type',
        'personnel_info.personnel_category': '$user_info.personnel_info.personnel_category',
        'personnel_info.personnel_classification': '$user_info.personnel_info.personnel_classification',
        'personnel_category': '$user_info.personnel_info.personnel_category',
        'personnel_classification': '$user_info.personnel_info.personnel_classification',
        'personnel_info.sex': '$user_info.personnel_info.sex',
        'personnel_info.date_birth': '$user_info.personnel_info.date_birth',
        'telephone': '$user_info.personnel_info.telephone',
        'remarks': '$user_info.personnel_info.remarks',
        'card_number': '$user_info.personnel_info.card_number',
        'family_name': '$user_info.personnel_info.family_name',
        'nation': '$user_info.personnel_info.nation',
        'card_name': '$user_info.personnel_info.card_name',
        'native_place': '$user_info.personnel_info.native_place',
        'id_card_address': '$user_info.personnel_info.id_card_address',
        'account_name': '$user_info.login_info.login_check.account_name',
        # 'password': '$user_info.login_info.login_check.password',
        # 'contacts_telephone': '$user_info.personnel_info.contacts_telephone',
        # 'contacts': '$user_info.personnel_info.contacts',
        'address': '$user_info.personnel_info.address',
        'role_id': '$user_info.personnel_info.role_id',
        'admin_area_id': '$user_info.admin_area_id',
        'date_birth': '$user_info.personnel_info.date_birth',
        'sex': '$user_info.personnel_info.sex',
        'create_date': '$user_info.create_date'
        # 'personnel_info': '$user_info.personnel_info'
    }

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.import_excel_servie = ImportExcelService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_current_user_info(self):
        '''获取当前用户信息'''
        user_id = get_current_user_id(self.session)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == user_id)\
               .project({'_id': 0, })
        res = self.query(_filter, self.user_collection)

        if len(res) > 0:
            # 查询当前登录的角色ID
            role_id = get_current_role_id(self.session)

            # 找到角色ID对应的role_name
            _filter_role = MongoBillFilter()
            _filter_role.match_bill(C('id') == role_id)\
                .project({'_id': 0, })
            role_id_res = self.query(_filter_role, 'PT_Role')

            # 补全角色ID
            res[0]['role_id'] = role_id

            # 补全角色名
            if len(role_id_res) > 0 and 'name' in role_id_res[0]:
                res[0]['db_role_name'] = role_id_res[0]['name']
                res[0]['db_role_type'] = role_id_res[0]['role_type']
            else:
                res[0]['db_role_name'] = '暂无'
                res[0]['db_role_type'] = '暂无'

        return res

    # def get_user_list(self, org_list, permission_condition, condition, page, count):
    #     '''获取用户列表'''
    #     keys = ['name', 'id_card']
    #     values = self.get_value(condition, keys)
    #     permission_keys = ['user_type']
    #     permission_values = self.get_value(
    #         permission_condition, permission_keys)
    #     _filter = MongoBillFilter()
    #     _filter.inner_join_bill('PT_User_Relationship', 'id', 'main_relation_people', 'relation_info')\
    #            .inner_join_bill('PT_User', 'relation_info.subordinate_relation_people', 'id', 'user_info')\
    #            .match((C('user_info.personnel_type') == UserType.Personnel)
    #                   & (C('user_info.name').like(values['name']))
    #                   & (C('user_info.personnel_info.id_card') == values['id_card'])
    #                   & (C('user_info.personnel_info.personnel_category').inner(permission_values['user_type']))
    #                   & (C('organization_id').inner(org_list)))\
    #            .project({'name': '$user_info.name', 'id_card': '$user_info.id_card', 'id_card_type': '$user_info.id_card_type', 'personnel_info.personnel_category': '$user_info.personnel_info.personnel_category'})
    #     res = self.page_query(_filter, "PT_User", page, count)
    #     return res

    def get_user_elder_list(self, org_list, condition, page, count):
        '''获取当前登录账号入住长者列表 现在的用法已经转变为查询全部长者了'''
        keys = ['name', 'id_card', 'id', 'tel', 'die_state',
                'is_member', 'marriage_state', 'address', 'organization_name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('organization_id').inner(org_list))
                           & (C('personnel_type') == UserType.Personnel)
                           & (C('personnel_info.personnel_category') == '长者')
                           & (C('personnel_info.telephone') == values['tel'])
                           & (C('name').like(values['name']))
                           & (C('id_card').like(values['id_card']))
                           & (C('id') == values['id'])
                           & (C('personnel_info.die_state') == values['die_state'])
                           & (C('personnel_info.is_member') == values['is_member'])
                           & (C('personnel_info.marriage_state') == values['marriage_state'])
                           & (C('personnel_info.address').like(values['address']))
                           )\
            .lookup_bill('PT_Personnel_Classification', 'personnel_info.personnel_classification', 'id', 'old_type')\
            .inner_join_bill('PT_User', 'organization_id', 'id', 'org')\
            .match_bill(C('org.name').like(values['organization_name']))\
            .sort({'modify_date': -1})\
            .project({'_id': 0, 'old_type._id': 0, 'org._id': 0})
        res = self.page_query(_filter, 'PT_User', page, count)
        print(res)
        for i, x in enumerate(res['result']):
            data = res['result'][i]['personnel_info']
            if 'date_birth' in data.keys() and data['date_birth'] != '' and data['date_birth'] != None:
                date_res = get_string_time(data['date_birth'], '%Y-%m-%d')
                data['date_birth'] = date_res
                data['age'] = get_str_to_age(date_res)
        return res

    def get_elder_list(self, org_list, condition, page, count):
        '''查询长者列表，单纯查询长者的信息'''
        keys = ['name', 'id_card', 'id', 'tel']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('personnel_info.personnel_category') == '长者')
                           & (C('organization_id').inner(org_list))
                           & (C('personnel_type') == UserType.Personnel)
                           & (C('personnel_info.telephone') == values['tel'])
                           & (C('name').like(values['name']))
                           & (C('id_card').like(values['id_card']))
                           & (C('id') == values['id'])
                           )\
            .sort({'modify_date': -1})\
            .project({'_id': 0})
        res = self.page_query(_filter, 'PT_User', page, count)
        return res

    def get_elder_list_by_org(self, org_list, condition, page, count):
        '''获取当前机构下入住的长者'''
        keys = ['name', 'id_card', 'id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('organization_id') == get_current_organization_id(self.session)) & (C('state') == CheckInStatus.check_in.value))\
            .inner_join_bill('PT_User', 'user_id', 'id', 'user_info')\
            .match((C('user_info.personnel_info.personnel_category') == '长者')
                   & (C('user_info.name').like(values['name']))
                   & (C('user_info.id_card').like(values['id_card']))
                   & (C('user_info.id') == values['id']))\
            .project(self.project_condition)
        res = self.page_query(_filter, 'IEC_Check_In', page, count)
        return res

    def get_user_worker_list(self, org_list, condition, page, count):
        '''获取工作人员列表'''
        keys = ['name', 'id_card', 'id', 'organization_name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('name').like(values['name']))
                           & (C('id_card').like(values['id_card']))
                           & (C('id') == values['id'])
                           & (C('personnel_info.personnel_category') == '工作人员'))\
               .inner_join_bill('PT_User', 'organization_id', 'id', 'org')\
               .lookup_bill('PT_Set_Role', 'id', 'principal_account_id', 'setRole')\
               .add_fields({'new_field': self.ao.array_filter("$setRole", "aa", ((F('$aa.role_of_account_id').inner(org_list))).f)})\
               .match((C("new_field") != None) & (C("new_field") != []))\
               .match((C("org.name").like(values['organization_name'])))\
               .sort({'create_date': -1})\
               .project({'_id': 0, 'setRole._id': 0, 'new_field._id': 0, 'org._id': 0})
        res = self.page_query(_filter, 'PT_User', page, count)
        for i, x in enumerate(res['result']):
            data = res['result'][i]['personnel_info']
            if 'date_birth' in data.keys() and data['date_birth'] != '' and data['date_birth'] != None:
                date_res = get_string_time(data['date_birth'], '%Y-%m-%d')
                data['date_birth'] = date_res
                data['age'] = get_str_to_age(date_res)
        return res

    def get_user_all_list(self, org_list, condition, page, count):
        '''获取当前机构的工作人员和平台游客列表'''
        keys = ['name', 'id_card', 'id', 'type']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('role_of_account_id').inner(org_list)) | (C('role_id') == self.plat_visitor_id))\
               .group({'user_id': '$principal_account_id'})\
               .inner_join_bill('PT_User', 'user_id', 'id', 'user_info')\
               .match((C('user_info.name').like(values['name']))
                      & (C('user_info.id') == (values['id']))
                      & (C('user_info.personnel_info.personnel_category').like(values['type'])))\
               .project(self.project_condition)
        res = self.page_query(_filter, 'PT_Set_Role', page, count)
        for i, x in enumerate(res['result']):
            data = res['result'][i]['personnel_info']
            if 'date_birth' in data.keys() and data['date_birth'] != '' and data['date_birth'] != None:
                date_res = get_string_time(data['date_birth'], '%Y-%m-%d')
                data['date_birth'] = date_res
                data['age'] = get_str_to_age(date_res)
        return res

    def update_elder_info(self, condition):
        user = self.get_current_user_info()
        condition['modify_date'] = get_cur_time()
        extend_info = {}
        if 'personnel_info' in condition.keys() and 'card_number' in condition['personnel_info'].keys():
            extend_info['card_number'] = condition['personnel_info']['card_number']
        if 'personnel_info' in condition.keys() and 'card_name' in condition['personnel_info'].keys():
            extend_info['card_name'] = condition['personnel_info']['card_name']
        if 'admin_area_id' not in condition.keys():
            condition['admin_area_id'] = user[0]['admin_area_id']
        res = {'id': '', 'res': 'Fail'}
        if 'id' in condition.keys():
            # 这里要做一个判断是否已存在该人员的判断：没有登录账号信息则合并，有登录账号信息则提示已存在
            _filter = MongoBillFilter()
            _filter.match_bill((C('name') == condition['name']) & (C('id_card') == condition['id_card']))\
                .project({'_id': 0, })
            query_res = self.query(_filter, 'PT_User')
            if len(query_res) > 0 and query_res[0]['id'] != condition['id']:
                return {'id': '', 'res': '该长者：' + condition['name'] + '已存在，无需重新注册'}
            # 这里判断当前账号是否已存在
            if condition['login_info'][0]['login_check']['account_name'] and condition['login_info'][0]['login_check']['account_name'] != '':
                _filter = MongoBillFilter()
                _filter.add_fields({'account_name': self.ao.array_filter("$login_info", "info", ((F('info.login_check.account_name') == condition['login_info'][0]['login_check']['account_name'])).f)})\
                    .match_bill((C("account_name") != None) & (C("account_name") != []))\
                    .project({'_id': 0, })
                res_account = self.query(_filter, 'PT_User')
                if len(res_account) > 0 and res_account[0]['id'] != condition['id']:
                    return {'id': '', 'res': '登录账号：'+condition['login_info'][0]['login_check']['account_name'] + '已存在，不能重复'}
            # 查一下该人员的信息,延用该账号原本密码
            _filter = MongoBillFilter()
            _filter.match_bill((C('id') == condition['id']))\
                .project({'_id': 0})
            res_user = self.query(_filter, 'PT_User')
            if len(res_user) > 0 and 'login_info' in res_user[0].keys() and len(res_user[0]['login_info']) > 0:
                login_check = res_user[0]['login_info'][0]['login_check']
                if 'password' in login_check.keys():
                    password = res_user[0]['login_info'][0]['login_check']['password']
                    condition['login_info'][0]['login_check']['password'] = password
            time = condition['personnel_info']['date_birth']
            condition['personnel_info']['date_birth'] = string_to_date(time)
            data = condition
            table = 'PT_User'
            if extend_info:
                # 查找长者真实账户id
                _filter = MongoBillFilter()
                _filter.match_bill((C('user_id') == condition['id'])
                                   & (C('account_type') == AccountType.account_real))\
                    .project({'_id': 0})
                res_real = self.query(_filter, FinancialAccount().name)
                if len(res_real) > 0:
                    data = [condition, {'id': res_real[0]
                                        ['id'], 'extend_info':extend_info}]
                    table = ['PT_User', FinancialAccount().name]

            bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                        TypeId.user.value, data, table)
            # 新增或者编辑set_role表
            # 查找set_role表
            _filter = MongoBillFilter()
            _filter.match_bill((C('principal_account_id') == condition['id']))\
                .project({'_id': 0})
            res_set_role = self.query(_filter, 'PT_Set_Role')
            if(condition['personnel_info']['personnel_category'] == '长者'):
                set_role = {'role_id': '8ed260f6-e355-11e9-875e-a0a4c57e9ebe',
                            'principal_account_id': condition['id'], 'role_of_account_id': condition['organization_id']}
            else:
                set_role = {'role_id': condition['personnel_info']['role_id'],
                            'principal_account_id': condition['id'], 'role_of_account_id': condition['organization_id']}
            if len(res_set_role) > 0 and len(res_set_role) == 1:
                # 更新
                set_role['id'] = res_set_role[0]['id']
                flag = OperationType.update.value
            else:
                # 新增
                flag = OperationType.add.value

            bill_id = self.bill_manage_service.add_bill(
                flag, TypeId.setRole.value, set_role, 'PT_Set_Role')
            if bill_id:
                res = {'id': condition['id'], 'res': 'Success'}
        else:
            # 这里要做一个判断是否已存在该人员的判断：没有登录账号信息则合并，有登录账号信息则提示已存在
            _filter = MongoBillFilter()
            _filter.match_bill((C('name') == condition['name']) & (C('id_card') == condition['id_card']))\
                   .inner_join_bill('PT_User', 'organization_id', 'id', 'org')\
                   .inner_join_bill('PT_Set_Role', 'id', 'principal_account_id', 'set_role')\
                   .lookup_bill('PT_Financial_Account', 'id', 'user_id', 'financial')\
                .project({'_id': 0, 'org._id': 0, 'set_role._id': 0, 'financial._id': 0})
            query_res = self.query(_filter, 'PT_User')
            flag = True
            # 暂时开放 query_res[0]['org']['id'] != '8476556c-26ff-11ea-8c15-a0a4c57e9ebe'，解决福利院讲政府备案的长者转到其组织机构下的问题
            if len(query_res) > 0:
                if query_res[0]['org']['id'] == '8476556c-26ff-11ea-8c15-a0a4c57e9ebe':
                    condition['id'] = query_res[0]['id']
                    flag = False
                else:
                    return {'id': '', 'res': '该长者：' + condition['name'] + '已存在，无需重新注册'}
            if flag:
                # 这里判断当前账号是否已存在
                if (condition['login_info'][0]['login_check']['account_name'] != ''):
                    _filter = MongoBillFilter()
                    _filter.add_fields({'account_name': self.ao.array_filter("$login_info", "info", ((F('$info.login_check.account_name') == condition['login_info'][0]['login_check']['account_name'])).f)}).match_bill((C("account_name") != None) & (C("account_name") != []))\
                        .project({'_id': 0, })
                    res_account = self.query(_filter, 'PT_User')
                    if len(res_account) > 0:
                        return {'id': '', 'res': '登录账号：'+condition['login_info'][0]['login_check']['account_name'] + '已存在，不能重复'}
                # 初始密码
                new_password = '000000'
                newpassword_tep = hashlib.sha256(new_password.encode('utf-8'))
                newpassword = newpassword_tep.hexdigest()
                condition['login_info'][0]['login_check']['password'] = newpassword
                data_id = get_info({}, self.session)
                condition['id'] = data_id['id']
                time = condition['personnel_info']['date_birth']
                condition['personnel_info']['date_birth'] = string_to_date(
                    time)
                if 'organization_id' in condition.keys() and condition['organization_id'] != '':
                    org_id = condition['organization_id']
                else:
                    org_id = get_current_organization_id(self.session)
                    condition['organization_id'] = org_id
                if(condition['personnel_info']['personnel_category'] == '长者'):
                    set_role = {'role_id': '8ed260f6-e355-11e9-875e-a0a4c57e9ebe',
                                'principal_account_id': data_id['id'], 'role_of_account_id': org_id}
                else:
                    set_role = {'role_id': condition['personnel_info']['role_id'],
                                'principal_account_id': data_id['id'], 'role_of_account_id': org_id}

                self.bill_manage_service.add_bill(OperationType.add.value,
                                                  TypeId.setRole.value, set_role, 'PT_Set_Role')
                # 新增账户信息（1个机构储蓄、1个app储蓄、1个真实账户、1个补贴账户）
                # 机构储蓄对象
                org_account_data = FinancialAccountObject(
                    AccountType.account_recharg_wel, data_id['id'], org_id, AccountStatus.normal, 1, AccountType.account_recharg_wel, {}, 0)
                org_account = get_info(
                    org_account_data.to_dict(), self.session)
                # app储蓄对象
                app_account_data = FinancialAccountObject(
                    AccountType.account_recharg_app, data_id['id'], plat_id, AccountStatus.normal, 2, AccountType.account_recharg_app, {}, 0)
                app_account = get_info(
                    app_account_data.to_dict(), self.session)
                # 真实账户对象
                real_account_data = FinancialAccountObject(
                    AccountType.account_real, data_id['id'], None, AccountStatus.normal, 3, AccountType.account_real, extend_info, 0)
                real_account = get_info(
                    real_account_data.to_dict(), self.session)
                # 补贴账户对象
                subsidy_account_data = FinancialAccountObject(
                    AccountType.account_subsidy, data_id['id'], None, AccountStatus.normal, 4, AccountType.account_subsidy, {}, 0)
                subsidy_account = get_info(
                    subsidy_account_data.to_dict(), self.session)

                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.user.value, [[condition], [org_account, app_account, real_account, subsidy_account]], ['PT_User', FinancialAccount().name])
                if bill_id:
                    res = {'id': condition['id'], 'res': 'Success'}
            else:
                set_role = query_res[0]['set_role']
                set_role['role_of_account_id'] = condition['organization_id']
                set_role['organization_id'] = condition['organization_id']
                account = query_res[0]['financial']
                if len(account):
                    pf = pd.DataFrame(account)
                    pf['organization_id'] = condition['organization_id']
                    account = dataframe_to_list(pf)
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value, TypeId.user.value, [
                    condition, set_role, account], ['PT_User', 'PT_Set_Role', FinancialAccount().name])
                if bill_id:
                    res = {'id': condition['id'], 'res': 'Success'}

        return res

    def delete_elder_info(self, condition):
        ids = []
        if isinstance(condition, str):
            ids.append({"id": condition})
        else:
            for id_str in condition:
                ids.append({"id": id_str})
        self.bill_manage_service.add_bill(OperationType.delete.value,
                                          TypeId.user.value, ids, 'PT_User')
        res = 'Success'
        return res

    def get_organization_list(self, org_list, condition, page, count):
        '''获取组织机构列表'''
        def convertDegreesToRadians(degrees):
            return degrees * math.pi / 180

        def coverGpsToBaiduLatLon(lat, lon):
            baidu_map_url = 'http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x=%f&y=%f'

            data_req = requests.get((baidu_map_url % (lon, lat)))
            new_pos = data_req.json()
            if 'error' in new_pos.keys() and new_pos['error'] == 0:
                lon = float(base64.b64decode(
                    new_pos['x']).decode("utf-8"))
                lat = float(base64.b64decode(
                    new_pos['y']).decode("utf-8"))
                return lat, lon

        keys = ['id', 'name', 'organization_nature',
                'personnel_category', 'personnel_type', 'lat', 'lon', 'sortByDistance']
        values = self.get_value(condition, keys)

        _filter = MongoBillFilter()
        if org_list != [None]:
            _filter.match((C('id').inner(org_list)))
        _filter.filter_objects
        _filter.match_bill((C('id') == values['id'])
                           & (C('personnel_type') == '2')
                           & (C('name').like(values['name']))
                           & (C('organization_info.organization_nature').like(values['organization_nature']))
                           & (C('personnel_type') == values['personnel_type'])
                           & (C('organization_info.personnel_category') == values['personnel_category']))\
               .lookup_bill('PT_User', 'organization_info.super_org_id', 'id', 'organization_infos')\
               .lookup_bill('PT_Activity', 'id', 'organization_id', 'organization_activity')\
               .add_fields({'activity_count': self.ao.size('$organization_activity'), })\
               .add_fields({"activity_id": self.ao.array_elemat("$organization_activity.id", 0)})\
               .lookup_bill('PT_Activity_Participate', 'activity_id', 'activity_id', 'organization_participate')\
               .add_fields({'participate_count': self.ao.size('$organization_participate'), })\
               .lookup_bill('PT_Service_Follow_Collection', 'id', 'business_id', 'follow_info')\
               .add_fields({'follow_count': self.ao.size('$follow_info'), })\
               .lookup_bill('PT_Administration_Division', 'admin_area_id', 'id', 'division_info')\
               .add_fields({"division_name": self.ao.array_elemat("$division_info.name", 0)})\
               .lookup_bill('PT_Bed', 'id', 'organization_id', 'bed')\
               .add_fields({'bed_count': self.ao.size('$bed'), })\
               .add_fields({'chenk_in_count': self.ao.size(self.ao.array_filter("$bed", "aa", ((F('$aa.residents_id') != None) & (F('$aa.residents_id') != '')).f))})\
               .add_fields({'organization_info.chenk_in_probability': self.ao.floor(self.ao.switch([self.ao.case(((F('bed_count') == 0)), 0)], (F('chenk_in_count').__truediv__('$bed_count') * (100)).f))})\
               .lookup_bill('PT_Service_Product', 'id', 'organization_id', 'service_product')
        user_id = get_user_id_or_false(self.session)
        if user_id != False:
            _filter.add_fields({'is_follow': self.ao.size(self.ao.array_filter(
                "$follow_info", "fi", ((F('$fi.user_id') == user_id) & (F('$fi.object') == '社区幸福院') & (F('$fi.type') == 'follow')).f))})
        if 'sort' in condition and condition['sort'] != None:
            if condition['sort'] == '活动数':
                _filter.sort({'activity_count': -1})
            elif condition['sort'] == '报名数':
                _filter.sort({'participate_count': -1})
            elif condition['sort'] == '关注度':
                _filter.sort({'follow_count': -1})
            elif condition['sort'] == '入住率':
                _filter.sort({'organization_info.chenk_in_probability': -1})
            else:
                _filter.sort({'create_date': -1})

        _filter.project({'_id': 0, 'bed._id': 0, 'chenk_in': 0, 'service_product': 0, 'organization_infos._id': 0,
                         'organization_activity': 0, 'organization_participate': 0, 'division_info': 0, 'follow_info': 0, 'order_info': 0})
        if 'lat' in condition and 'lon' in condition:
            lat = values['lat']
            lon = values['lon']
            # 纬度，经度
            lat_baidu, lon_baidu = coverGpsToBaiduLatLon(lat, lon)
            lat_d = convertDegreesToRadians(lat_baidu)
            # _filter.add_fields({'distance':self.ao.multiply([self.ao.acos(self.ao.add([self.ao.multiply([self.ao.sin(self.ao.degree_to_radians(self.ao.to_double("$organization_info.lat"))),
            #                                                                                              self.ao.sin(lat_d)]),
            #                                                                            self.ao.multiply([self.ao.cos(self.ao.degree_to_radians(self.ao.to_double("$organization_info.lat")))
            #                                                                                             ,self.ao.cos(lat_d)
            #                                                                                             ,self.ao.cos(self.ao.degree_to_radians(self.ao.substract[self.ao.to_double('$organization_info.lon')
            #                                                                                                                                                     ,lon_baidu]))])])),6371.004])})
            _filter.filter_objects.append({
                '$addFields': {
                    # 距离是以km单位的
                    "distance": {
                        '$multiply': [
                            {
                                '$acos': {
                                    '$add': [
                                        {
                                            '$multiply': [
                                                {
                                                    '$sin': {'$degreesToRadians': {"$toDouble": "$organization_info.lat"}}
                                                },
                                                {
                                                    '$sin': lat_d
                                                }
                                            ]
                                        },
                                        {
                                            '$multiply': [
                                                {
                                                    '$cos': {'$degreesToRadians': {"$toDouble": "$organization_info.lat"}}
                                                },
                                                {
                                                    '$cos': lat_d
                                                },
                                                {
                                                    '$cos': {
                                                        '$degreesToRadians': {
                                                            '$subtract': [
                                                                {"$toDouble": "$organization_info.lon"},
                                                                lon_baidu
                                                            ]
                                                        }
                                                    }
                                                }
                                            ]
                                        }
                                    ]
                                }
                            },
                            # 地球平均半径
                            6371.004
                        ]
                    }
                }
            })
        else:
            _filter.add_fields({'distance': None})

        if 'sortByDistance' in condition:
            _filter.sort({'distance': 1})\
                # print(_filter.filter_objects)
        res = self.page_query(_filter, 'PT_User', page, count)

        return res

    def get_organization_tree_list(self, org_list, condition, page, count):
        '''查询 组织机构树形结构  '''
        _filter = MongoBillFilter()
        _filter.match_bill((C('personnel_type') == '2') & (C('id').inner(org_list)))\
            .add_fields({
                'title': '$name',
                'value': '$id',
                'key': '$id',
                'children': []
            })\
            .project({'_id': 0})
        res = self.page_query(_filter, 'PT_User', page, count)
        result = []
        if len(res['result']) > 0:
            for data in res['result']:
                new_res = self.query_child(data['id'], condition)
                r_data = self.xuhuan(new_res, data, condition)
                result.append(r_data)
        res['result'] = result
        return res

    def xuhuan(self, new_res, return_data, condition):
        if len(new_res) > 0:
            return_data['children'] = new_res
            for data in new_res:
                child_data = self.query_child(data['id'], condition)
                self.xuhuan(child_data, data, condition)
        return return_data

    def query_child(self, org_id, condition):
        keys = ['organization_type']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('organization_info.super_org_id') == org_id) & (C('organization_info.personnel_category') == values['organization_type']))\
            .add_fields({
                'title': '$name',
                'value': '$id',
                'key': '$id',
                'children': []
            })\
            .project({'_id': 0})
        res = self.query(
            _filter, "PT_User")
        return res

    def judge_is_success(self, self_org_id, select_org_id):
        '''
            用于判断选择上级组织机构时，选择的机构是否正确（不为本组织的下级或自身）有个问题：如果选的是上级理论上应该无条件成功，但现在会递归所有下级，导致卡死
            解决方案：应该给组织机构分层级
            self_org_id: 本次编辑的组织机构Id
            select_org_id: 选择的组织机构Id
        '''
        flag = True
        if select_org_id == self_org_id:
            flag = False
            return flag
        ''' 暂时先注释，有解决选了上级会多重循环下级的方案后再放开'''
        # _filter = MongoBillFilter()
        # _filter.match_bill((C('organization_info.super_org_id') == self_org_id))\
        #     .project({'_id': 0})
        # res = self.query(_filter, 'PT_User')
        # for result in res:
        #     if result['id'] == select_org_id:
        #         flag = False
        #         return flag
        #     else:
        #         flag = self.judge_is_success(result['id'], select_org_id)
        #         if not flag:
        #             return flag
        return flag

    def update_organization(self, condition):
        '''新增/修改组织机构'''
        user = self.get_current_user_info()
        if 'admin_area_id' not in condition.keys():
            condition['admin_area_id'] = user[0]['admin_area_id']
        res = 'Fail'
        if 'id' in condition.keys():
            resl = self.judge_is_success(
                condition['id'], condition['organization_info']['super_org_id'])
            if not resl:
                return '不能选择当前组织机构'

            _filter = MongoBillFilter()
            _filter.match_bill(
                (C('organization_info.super_org_id') == condition['id'])).project({'_id': 0})
            parent_data = self.query(_filter, "PT_User")
            _filter_old = MongoBillFilter()
            _filter_old.match_bill(
                (C('id') == condition['id'])).project({'_id': 0})
            old_data = self.query(_filter_old, "PT_User")
            if len(parent_data) > 0 and old_data[0]['organization_info']['super_org_id'] != condition['organization_info']['super_org_id']:
                return '该组织机构已有下级关联，不能更改上级组织机构'

            bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                        TypeId.organization.value, condition, 'PT_User')
            if bill_id:
                res = 'Success'
        else:
            # resl = self.judge_is_success(
            #     get_current_organization_id(self.session), condition['organization_info']['super_org_id'])
            # if not resl:
            #     return '不能选择当前组织机构'
            data = condition
            tables = 'PT_User'
            data_id = get_info({}, self.session)
            condition['id'] = data_id['id']
            # 组织类型为福利院
            if condition['organization_info']['personnel_category'] == '福利院':
                # 新增一个真实账户
                # 真实账户对象
                real_account_data = FinancialAccountObject(
                    AccountType.account_real, data_id['id'], None, AccountStatus.normal, 1, AccountType.account_real, {}, 0)
                real_account = get_info(
                    real_account_data.to_dict(), self.session)
                condition['agent_account'] = real_account['id']
                condition['main_account'] = real_account['id']
                data = [condition, real_account]
                tables = ['PT_User', FinancialAccount().name]

            # 组织类型为服务商
            if condition['organization_info']['personnel_category'] == '服务商':
                # 新增一个真实账户 + 补贴账户
                # 真实账户对象
                real_account_data = FinancialAccountObject(
                    AccountType.account_real, data_id['id'], None, AccountStatus.normal, 1, AccountType.account_real, {}, 0)
                real_account = get_info(
                    real_account_data.to_dict(), self.session)
                condition['agent_account'] = real_account['id']
                condition['main_account'] = real_account['id']
                # 补贴账户
                subsidy_account_data = FinancialAccountObject(
                    AccountType.account_subsidy, data_id['id'], None, AccountStatus.normal, 2, AccountType.account_subsidy, {}, 0)
                subsidy_account = get_info(
                    subsidy_account_data.to_dict(), self.session)
                data = [[condition], [real_account, subsidy_account]]
                tables = ['PT_User', FinancialAccount().name]

            bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                        TypeId.organization.value, data, tables)
            if bill_id:
                res = 'Success'
        return res

    def delete_organization(self, condition):
        ids = []
        current_org_id = get_current_organization_id(self.session)
        if isinstance(condition, str):
            ids.append({"id": condition})
            if current_org_id == condition:
                return '不能删除当前组织机构'
        else:
            for id_str in condition:
                ids.append({"id": id_str})
                if current_org_id == id_str:
                    return '不能删除当前组织机构'
        self.bill_manage_service.add_bill(OperationType.delete.value,
                                          TypeId.organization.value, ids, 'PT_User')
        res = 'Success'
        return res

    def get_wait_checkin_elder_list(self, org_list, condition, page, count):
        keys = ['id', 'name']
        values = self.get_value(condition, keys)
        _fliter = MongoBillFilter()
        _fliter.match_bill(
            (C('organization_id').inner(org_list))
            & (C('state') == '居住中')
        )
        res = self.query(_fliter, 'IEC_Check_In')
        pf = pd.DataFrame(res)
        user_list = []
        if 'user_id' in pf:
            user_list = pf['user_id'].tolist()
        _filter_wait = MongoBillFilter()
        _filter_wait.match_bill(
            (C('name').like(values['name']))
            & (C('organization_id').inner(org_list))
            & (C('id').nin(user_list))
            & (C('personnel_info.personnel_category') == '长者')
        ) \
            .inner_join_bill('PT_Behavioral_Competence_Assessment_Record', 'id', 'elder', 'recode') \
            .inner_join_bill('PT_Assessment_Template', 'recode.template', 'id', 'template') \
            .match_bill(C('template.template_type') == '详细能力评估')\
            .project({'_id': 0, 'template': 0, 'recode._id': 0})
        user_wait = self.page_query(_filter_wait, 'PT_User', None, None)
        return user_wait

    def get_personnel_classification_list(self, org_list, condition, page, count):
        '''获取人员类别列表
        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        keys = ['id', 'name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('name').like(values['name']))
                           & (C('organization_id').inner(org_list)))\
            .project({'_id': 0})
        res = self.page_query(
            _filter, 'PT_Personnel_Classification', page, count)
        return res

    def update_personnel_classification(self, data):
        '''新增或修改人员类别'''
        res = 'Fail'
        if 'id' in list(data.keys()):
            bill_id = self.bill_manage_service.add_bill(
                OperationType.update.value, TypeId.personnelClassification.value, data, 'PT_Personnel_Classification')
            if bill_id:
                res = 'Success'
        else:
            bill_id = self.bill_manage_service.add_bill(
                OperationType.add.value, TypeId.personnelClassification.value, data, 'PT_Personnel_Classification')
            if bill_id:
                res = 'Success'
        return res

    def delete_personnel_classification(self, data):
        '''删除人员类别'''
        res = 'Fail'

        if len(data) > 0:

            ids = []

            for item in data:
                # 判断是否使用中
                _filter = MongoBillFilter()
                _filter.match_bill(
                    (C('personnel_info.personnel_classification') == item))
                _filter.project({'_id': 0})

                res_user = self.query(_filter, 'PT_User')

                if len(res_user) > 0:
                    return '该人员类别使用中，无法删除'

                ids.append({"id": item})

            bill_id = self.bill_manage_service.add_bill(OperationType.delete.value,
                                                        TypeId.personnelClassification.value, ids, 'PT_Personnel_Classification')
            if bill_id:
                res = 'Success'

        return res

    def get_organization_xfy_tree_list(self, org_list, condition, page, count):
        ''' 查询幸福院树状列表 '''
        # 获取当前组织机构的行政区划Id
        _filter = MongoBillFilter()
        _filter.match_bill((C('id').inner(org_list)))\
            .project({'_id': 0})
        res_user = self.query(
            _filter, "PT_User")
        admin_area_id = ''
        if len(res_user) > 0:
            admin_area_id = res_user[0]['admin_area_id']
        # keys = ['id', 'name', 'is_no_myself']
        # values = self.get_value(condition, keys)
        # permission_keys = ['user_type']
        # permission_values = self.get_value(
        #     permission_condition, permission_keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == admin_area_id))\
            .add_fields({
                'title': '$name',
                'value': '$id',
                'key': '$id',
                'children': [],
                # 标识这是一个行政区域
                'is_division': True,
            })\
            .project({'_id': 0})
        res = self.page_query(
            _filter, "PT_Administration_Division", page, count)
        result = []
        if len(res['result']) > 0:
            for data in res['result']:
                new_res = self.query_child2(data['id'])
                r_data = self.xuhuan2(new_res, data)
                result.append(r_data)

        res['result'] = result
        return res

    def xuhuan2(self, new_res, return_data):
        if len(new_res) > 0:
            return_data['children'] = new_res
            # 应该在这里加幸福院吧
            for data in new_res:
                child_data = self.query_child2(data['id'])
                self.xuhuan2(child_data, data)
        return return_data

    def query_child2(self, admin_id):
        _filter = MongoBillFilter()
        _filter.match_bill((C('parent_id') == admin_id))\
            .add_fields({
                'title': '$name',
                'value': '$id',
                'key': '$id',
                # 标识这是一个行政区域
                'is_division': True,
                'children': []
            })\
            .project({'_id': 0})
        res = self.query(
            _filter, "PT_Administration_Division")

        if len(res) > 0:
            for item in res:
                xfyByAreaId = self.getXfyByAreaId(item['id'], '幸福院')
                if len(xfyByAreaId) > 0:
                    for itm in xfyByAreaId:
                        item['children'].append(itm)
        return res

    def getXfyByAreaId(self, admin_area_id, personnel_category):
        # 根据行政区域ID（admin_area_id）和机构类型（幸福院）列出列表
        condition = {
            'admin_area_id': admin_area_id,
            'personnel_category': personnel_category,
        }
        keys = ['personnel_category', 'admin_area_id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('admin_area_id') == values['admin_area_id']) & (C('organization_info.personnel_category') == values['personnel_category']))\
            .add_fields({
                'title': '$name',
                'value': '$id',
                'key': '$id',
                # 标识这是一个组织机构
                'is_division': False,
            })\
            .project({'_id': 0})
        res = self.query(
            _filter, "PT_User")

        return res

    def get_current_user_reservation_registration(self, condition, page, count):
        '''获取当前用户及其家人的机构预约记录'''
        keys = ['id', 'organization_id']
        values = self.get_value(condition, keys)
        user_ids = [get_current_user_id(self.session)]
        # 获取家人档案相关联的人员Id
        _filter = MongoBillFilter()
        _filter.match_bill((C("main_relation_people").inner(user_ids)))\
            .project({"_id": 0})
        user_res = self.query(_filter, "PT_User_Relationship")
        if len(user_res) > 0:
            for user in user_res:
                user_ids.append(user['subordinate_relation_people'])
        _filter = MongoBillFilter()
        _filter.match_bill((C('elder_id').inner(user_ids)) & (C('elder_id') == values['id']) & (C('organization_id') == values['organization_id']))\
            .lookup_bill('PT_User', 'elder_id', 'id', 'elder_info')\
            .lookup_bill('PT_User', 'organization_id', 'id', 'organization')\
            .sort({'create_date': -1})\
            .project({'_id': 0, 'organization._id': 0, 'elder_info._id': 0})
        res = self.page_query(
            _filter, 'PT_Reservation_Registration', page, count)
        return res

    def get_current_user_activity_participate(self, condition, page, count):
        '''获取当前用户活动报名记录'''
        user_id = get_current_user_id(self.session)
        print(user_id)
        _filter = MongoBillFilter()
        _filter.match(C('user_id') == user_id)\
            .lookup_bill('PT_Activity', 'activity_id', 'id', 'activity')\
            .lookup_bill('PT_User', 'activity.organization_id', 'id', 'organization')\
            .lookup_bill('PT_Activity_Participate', 'activity_id', 'activity_id', 'participate')\
            .add_fields({'participate_count': self.ao.size('$participate')})\
            .sort({'create_date': -1})\
            .project({'_id': 0, 'activity._id': 0, 'organization._id': 0, 'participate': 0})
        res = self.page_query(_filter, 'PT_Activity_Participate', page, count)
        if len(res['result']) > 0:
            if len(res['result'][0]['activity']) > 0:
                now = datetime.datetime.now()
                res['result'][0]['activity'][0]['now_data'] = now
        return res

    def get_current_user_allowance_manage(self, condition, page, count):
        '''获取当前用户补贴申请记录'''
        user_id = get_current_user_id(self.session)
        _filter = MongoBillFilter()
        _filter.match_bill(C('apply_user_id') == user_id)\
            .sort({'create_date': -1})\
            .project({'_id': 0, })
        res = self.page_query(_filter, 'PT_Allowance_Manage', page, count)
        return res

    def get_current_user_charitable_donate(self, condition, page, count):
        '''获取当前用户慈善申请记录'''
        user_id = get_current_user_id(self.session)
        _filter = MongoBillFilter()
        _filter.match_bill((C('apply_user_id') == user_id) & (C('donate_type') == '个人'))\
            .sort({'create_date': -1})\
            .project({'_id': 0, })
        res = self.page_query(_filter, 'PT_Charitable_Donate', page, count)
        return res

    def get_current_user_message_notice(self, org_list, condition, page, count):
        '''获取当前用户消息记录'''
        count = 99
        role_id = get_current_role_id(self.session)
        user_id = get_current_user_id(self.session)
        returnArray = []
        # 判断角色
        if self.checkPermission(role_id, '查看高龄津贴审核', '查询') == True:
            # if True == True:
            # 高龄津贴补助
            print('高龄津贴补助权限')
            _filter = MongoBillFilter()
            _filter.match_bill((C('message_state') == '未读') & (C('business_type') == 'old_age_allowance') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_Old_Age_Allowance', 'business_id', 'id', 'business_info')\
                .add_fields({'business_info': self.ao.array_elemat("$business_info", 0)})\
                .lookup_bill('PT_User', 'business_info.id_card_num', 'personnel_info.id_card', 'elder_info')\
                .add_fields({'elder_info': self.ao.array_elemat("$elder_info", 0)})\
                .match((C("business_info") != None) & (C("business_info") != []) & (C("elder_info") != None) & (C("elder_info") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'business_info._id': 0, 'elder_info._id': 0})
            res = self.page_query(_filter, 'PT_Message', page, count)
            returnArray.append({
                'name': '高龄津贴',
                'data': res
            })
        if self.checkPermission(role_id, '床位管理', '查询') == True:
            print('床位管理权限')
            # 床位预约信息
            _filter = MongoBillFilter()
            _filter.match_bill((C('message_state') == '未读') & (C('business_type') == 'rservation_registration') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_Reservation_Registration', 'business_id', 'id', 'business_info')\
                .add_fields({'business_info': self.ao.array_elemat("$business_info", 0)})\
                .lookup_bill('PT_User', 'business_info.elder_id', 'id', 'elder_info')\
                .add_fields({'elder_info': self.ao.array_elemat("$elder_info", 0)})\
                .match((C("business_info") != None) & (C("business_info") != []) & (C("elder_info") != None) & (C("elder_info") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'business_info._id': 0, 'elder_info._id': 0})
            res = self.page_query(_filter, 'PT_Message', page, count)
            returnArray.append({
                'name': '床位预约',
                'data': res
            })
        # if self.checkPermission(role_id, '活动列表', '查询') == True:
        if self.checkSpPermission(role_id, 'activityPublish', 2) == True:
            # 活动列表信息
            print('活动列表权限')
            _filter = MongoBillFilter()
            _filter.match_bill((C('message_state') == '未读') & (C('business_type') == 'activity') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_Activity', 'business_id', 'id', 'business_info')\
                .add_fields({'business_info': self.ao.array_elemat("$business_info", 0)})\
                .lookup_bill('PT_User', 'business_info.apply_user_id', 'id', 'elder_info')\
                .add_fields({'elder_info': self.ao.array_elemat("$elder_info", 0)})\
                .lookup_bill('PT_User', 'business_info.organization_id', 'id', 'org_info')\
                .add_fields({'org_info': self.ao.array_elemat("$org_info", 0)})\
                .match((C("business_info") != None) & (C("business_info") != []) & (C("elder_info") != None) & (C("elder_info") != []) & (C("org_info") != None) & (C("org_info") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'business_info._id': 0, 'elder_info._id': 0, 'org_info._id': 0})
            res = self.page_query(_filter, 'PT_Message', page, count)
            returnArray.append({
                'name': '活动信息',
                'data': res
            })
        # if self.checkPermission(role_id, '新闻管理', '查询') == True:
        if self.checkSpPermission(role_id, 'newsPublish', 2) == True:
            # 新闻管理信息
            print('资讯列表权限')
            _filter = MongoBillFilter()
            _filter.match_bill((C('message_state') == '未读') & (C('business_type') == 'article') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_Article', 'business_id', 'id', 'business_info')\
                .add_fields({'business_info': self.ao.array_elemat("$business_info", 0)})\
                .lookup_bill('PT_User', 'business_info.promulgator_id', 'id', 'elder_info')\
                .add_fields({'elder_info': self.ao.array_elemat("$elder_info", 0)})\
                .match((C("business_info") != None) & (C("business_info") != []) & (C("elder_info") != None) & (C("elder_info") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'business_info._id': 0, 'elder_info._id': 0})
            res = self.page_query(_filter, 'PT_Message', page, count)
            returnArray.append({
                'name': '养老资讯',
                'data': res
            })
        if self.checkPermission(role_id, '服务订单', '查询') == True:
            # 服务商的购买信息
            print('服务订单权限')
            _filter = MongoBillFilter()
            _filter.match_bill((C('message_state') == '未读') & (C('business_type') == 'service_order') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_Service_Order', 'business_id', 'id', 'business_info')\
                .add_fields({'business_info': self.ao.array_elemat("$business_info", 0)})\
                .lookup_bill('PT_User', 'business_info.purchaser_id', 'id', 'elder_info')\
                .add_fields({'elder_info': self.ao.array_elemat("$elder_info", 0)})\
                .lookup_bill('PT_Service_Product', 'business_info.origin_product.product_id', 'id', 'product_info')\
                .add_fields({'product_info': self.ao.array_elemat("$product_info", 0)})\
                .lookup_bill('PT_User', 'organization_id', 'id', 'org_info')\
                .add_fields({'org_info': self.ao.array_elemat("$org_info", 0)})\
                .match((C("business_info") != None) & (C("business_info") != []) & (C("elder_info") != None) & (C("elder_info") != []) & (C("product_info") != None) & (C("product_info") != []) & (C("org_info") != None) & (C("org_info") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'business_info._id': 0, 'elder_info._id': 0, 'business_info._id': 0, 'org_info._id': 0, 'product_info._id': 0})
            res = self.page_query(_filter, 'PT_Message', page, count)
            returnArray.append({
                'name': '服务产品',
                'data': res
            })
        if self.checkPermission(role_id, '报名列表', '查询') == True:
            # 报名列表信息
            print('活动报名列表权限')
            _filter = MongoBillFilter()
            _filter.match_bill((C('message_state') == '未读') & (C('business_type') == 'activity_participate') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_Activity_Participate', 'business_id', 'id', 'business_info')\
                .add_fields({'business_info': self.ao.array_elemat("$business_info", 0)})\
                .lookup_bill('PT_User', 'business_info.user_id', 'id', 'elder_info')\
                .add_fields({'elder_info': self.ao.array_elemat("$elder_info", 0)})\
                .lookup_bill('PT_Activity', 'business_info.activity_id', 'id', 'activity_info')\
                .add_fields({'activity_info': self.ao.array_elemat("$activity_info", 0)})\
                .match((C("business_info") != None) & (C("business_info") != []) & (C("elder_info") != None) & (C("elder_info") != []) & (C("activity_info") != None) & (C("activity_info") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'business_info._id': 0, 'elder_info._id': 0, 'activity_info._id': 0})
            res = self.page_query(_filter, 'PT_Message', page, count)
            returnArray.append({
                'name': '活动报名',
                'data': res
            })
        # if self.checkPermission(role_id, '慈善基金', '查询') == True:
        #     # 慈善基金申请信息
        #     _filter = MongoBillFilter()
        #     _filter.match_bill((C('message_state') == '未读') & (C('business_type') == 'title_fund'))\
        #         .lookup_bill('PT_Charitable_Donate', 'business_id', 'id', 'business_info')\
        #         .add_fields({'business_info': self.ao.array_elemat("$business_info", 0)})\
        #         .lookup_bill('PT_User', '$business_info.donate_user_id', 'id', 'elder_info')\
        #         .match((C("business_info") != None) & (C("business_info") != []) & (C("elder_info") != None) & (C("elder_info") != []))\
        #         .sort({'create_date': -1})\
        #         .project({'_id': 0, 'business_info._id': 0, 'elder_info._id': 0})
        #     res = self.page_query(_filter, 'PT_Message', page, count)
        #     returnArray.append({
        #         'name': '基金申请',
        #         'data': res
        #     })

        return returnArray

    def check_permission(self, condition):
        if 'method' not in condition:
            return '缺少合法的方法字段！'
        # 这是用来判断是否有审批的权限，资讯详情，活动详情
        if condition['method'] == 'audit':
            if 'type' not in condition or condition['type'] not in ['article', 'activity']:
                return '缺少验证类型！'
            step_no = 2
            if condition['type'] == 'article':
                condition_type = 'newsPublish'
            elif condition['type'] == 'activity':
                condition_type = 'activityPublish'
            result = {
                'code': 'Success',
                'isAudit': self.checkSpPermission(get_current_role_id(self.session), condition_type, step_no),
            }
        # 这是用来判断我的发布页面服务商超管或者幸福院系列，服务商超管就显示产品，幸福院系列就显示活动
        elif condition['method'] == 'release':
            role_id = get_current_role_id(self.session)

            result = {}
            # 服务商超管ID
            if self.checkPermission(role_id, '服务产品', '查询') == True:
                result['is_product'] = True
            # 幸福院超管和幸福院工作人员
            if self.checkPermission(role_id, '活动列表', '查询') == True:
                result['is_activity'] = True

        # 这是用来判断我的受理有哪些权限的
        elif condition['method'] == 'acceptance':
            role_id = get_current_role_id(self.session)

            result = []
            # 床位管理
            if self.checkPermission(role_id, '床位管理', '查询') == True:
                result.append({
                    'name': '床位预约',
                })
            # 高龄津贴
            if self.checkPermission(role_id, '查看高龄津贴审核', '查询') == True:
                result.append({
                    'name': '高龄津贴',
                })
            # 冠名基金
            if self.checkSpPermission(role_id, 'titleFundApply', 2) == True:
                result.append({
                    'name': '冠名基金',
                })
            # 养老资讯
            if self.checkSpPermission(role_id, 'newsPublish', 2) == True:
                result.append({
                    'name': '养老资讯',
                })
            # 活动信息
            if self.checkSpPermission(role_id, 'activityPublish', 2) == True:
                result.append({
                    'name': '活动信息',
                })
        return result

    def get_current_user_acceptance(self, org_list, condition, page, count):
        '''获取当前用户受理记录'''
        role_id = get_current_role_id(self.session)
        user_id = get_current_user_id(self.session)
        res = []
        if 'type' in condition:
            stype = condition['type']
        else:
            stype = False
        # 判断角色
        if stype == '床位预约' and self.checkPermission(role_id, '床位管理', '查询') == True:
            # 床位预约信息
            _filter = MongoBillFilter()
            _filter.match_bill((C('bill_status') == 'valid') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_User', 'elder_id', 'id', 'elder_info')\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'elder_info._id': 0})
            res = self.page_query(
                _filter, 'PT_Reservation_Registration', page, count)
        if stype == '高龄津贴' and self.checkPermission(role_id, '查看高龄津贴审核', '查询') == True:
            # 高龄津贴补助
            _filter = MongoBillFilter()
            _filter.match_bill((C('bill_status') == 'valid') & (C('organization_id').inner(org_list)))\
                .lookup_bill('PT_User', 'id_card_num', 'personnel_info.id_card', 'elder_info')\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'elder_info._id': 0})
            res = self.page_query(_filter, 'PT_Old_Age_Allowance', page, count)
        # if self.checkPermission(role_id, '冠名基金', '查询') == True:
        if stype == '冠名基金' and self.checkSpPermission(role_id, 'titleFundApply', 2) == True:

            # 获取审批定义id
            _filter_dtype = MongoBillFilter()
            _filter_dtype.match_bill((C('approval_type') == 'titleFundApply') & (C('organization_id').inner(org_list)))\
                .project({'_id': 0, })
            res_dtype = self.query(_filter_dtype, 'PT_Approval_Define')

            # 冠名基金
            _filter = MongoBillFilter()
            _filter.match_bill((C('donate_type') == '基金'))\
                .lookup_bill('PT_Approval_Process', 'id', 'business_id', 'proccess_info')\
                .add_fields({'proccess': self.ao.array_filter(
                    "$proccess_info", "fi", ((F('$fi.proccess_user_id') == user_id) & (F('$fi.define_id') == res_dtype[0]['id']) & ((F('$fi.status') == '通过') | (F('$fi.status') == '不通过'))).f)})\
                .match((C("proccess") != None) & (C("proccess") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'proccess_info._id': 0, 'proccess._id': 0})
            res = self.page_query(_filter, 'PT_Charitable_Donate', page, count)
        if stype == '养老资讯' and self.checkSpPermission(role_id, 'newsPublish', 2) == True:

            # 获取审批定义id
            _filter_dtype = MongoBillFilter()
            _filter_dtype.match_bill((C('approval_type') == 'newsPublish') & (C('organization_id').inner(org_list)))\
                .project({'_id': 0, })
            res_dtype = self.query(_filter_dtype, 'PT_Approval_Define')
            # 养老资讯
            _filter = MongoBillFilter()
            _filter.match_bill()\
                .lookup_bill('PT_Approval_Process', 'id', 'business_id', 'proccess_info')\
                .add_fields({'proccess': self.ao.array_filter(
                    "$proccess_info", "fi", ((F('$fi.proccess_user_id') == user_id) & (F('$fi.define_id') == res_dtype[0]['id']) & ((F('$fi.status') == '通过') | (F('$fi.status') == '不通过'))).f)})\
                .match((C("proccess") != None) & (C("proccess") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'proccess_info._id': 0, 'proccess._id': 0})

            _filter_type = MongoBillFilter()
            _filter_type.match_bill((C("name").like('新闻')) | (C("name").like('news'))).project(
                {"_id": 0})
            res_type = self.query(_filter_type, "PT_Article_Type")

            if len(res_type) > 0:
                _filter.match_bill((C('type_id') == res_type[0].get('id')))

            res = self.page_query(_filter, 'PT_Article', page, count)
        if stype == '活动信息' and self.checkSpPermission(role_id, 'activityPublish', 2) == True:

            # 获取审批定义id
            _filter_dtype = MongoBillFilter()
            _filter_dtype.match_bill((C('approval_type') == 'activityPublish') & (C('organization_id').inner(org_list)))\
                .project({'_id': 0, })
            res_dtype = self.query(_filter_dtype, 'PT_Approval_Define')
            # 活动信息
            _filter = MongoBillFilter()
            _filter.match_bill()\
                .lookup_bill('PT_Approval_Process', 'id', 'business_id', 'proccess_info')\
                .add_fields({'proccess': self.ao.array_filter(
                    "$proccess_info", "fi", ((F('$fi.proccess_user_id') == user_id) & (F('$fi.define_id') == res_dtype[0]['id']) & ((F('$fi.status') == '通过') | (F('$fi.status') == '不通过'))).f)})\
                .match((C("proccess") != None) & (C("proccess") != []))\
                .sort({'create_date': -1})\
                .project({'_id': 0, 'proccess_info._id': 0, 'proccess._id': 0})

            res = self.page_query(_filter, 'PT_Activity', page, count)

        return res

    def checkSpPermission(self, role_id, define_type, step_no):
        # 根据define_type在PT_Approval_Define表检查这个帐号是否有审核的权限
        _filter = MongoBillFilter()
        _filter.match_bill((C('approval_type') == define_type))\
            .project({'_id': 0, })
        res = self.query(_filter, 'PT_Approval_Define')

        # 有这个权限
        if len(res) > 0 and 'approval_list' in res[0]:
            for item in res[0]['approval_list']:
                if item['step_no'] == step_no and item['approval_user_id'] == role_id:
                    return True

        return False

    def checkPermission(self, role_id, name, operation):
        # 根据permission表检测这个帐号是否有查看的权限
        _filter = MongoBillFilter()
        _filter.match_bill((C('role_id') == role_id) & (C('function') == name) & (C('permission') == operation))\
            .sort({'create_date': -1})\
            .project({'_id': 0, })
        res = self.query(_filter, 'PT_Permission')

        if len(res) > 0:
            return True
        else:
            return False

    def import_excel_manage(self, data):
        return self.import_excel_servie.import_excel_api(data)
